package com.icebergteam.warfacewidget.wiki.data;

import java.util.ArrayList;

import org.json.JSONObject;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.net.Uri;

import com.icebergteam.warfacewidget.core.LogManager;
import com.icebergteam.warfacewidget.core.Parser;
import com.icebergteam.warfacewidget.core.utils.ViewUtils;

public class WikiWidgetParser extends Parser  {
	final public static String className = WikiWidgetParser.class.getCanonicalName();
	
	
	public WikiWidgetParser() {
		super();
	}

	@Override
	public ArrayList<WikiWidgetItem> parseXML(Document doc, int limit) throws Exception {
		try {
			doc.normalise();
			Elements listItems = doc.select("div.wf_block table tr td:has(a img)");
			ArrayList<WikiWidgetItem> newsList = new ArrayList<WikiWidgetItem>();
			int index =0;
			for (Element item: listItems) {
				WikiWidgetItem tempItem = getItem(item);
				newsList.add(tempItem);
				index++;
				if(limit >= 0 && index == limit) break;
			}
			this.stateRequest = REQUEST_COMPLETED;
			return newsList;
		} 
		catch (Exception e) {
			this.stateRequest = WikiWidgetParser.XML_INVALID;

			throw new Exception(String.format(
					"%s - doc = %s; error = %s",  LogManager.getExecuteMethodName(), (doc == null) ? doc == null :doc.toString().substring(0, 300),
					ViewUtils.getErrorMessage(e)));
		}
	}
	
	@Override
	protected WikiWidgetItem getItem(org.jsoup.nodes.Element elem) throws Exception {
		WikiWidgetItem item = new WikiWidgetItem();
		item.setTitle(Uri.parse(Uri.decode(elem.select("a").first().attr("href"))).getLastPathSegment().replace("_", " "));//elem.select("a").first().attr("title"));
		item.setUrl(elem.select("a").first().attr("href"));
		item.setImgSrc(elem.select("a img").first().attr("src").replace("file://", ""));
		
		
		return item;
	}

	@Override
	public int saveData(String url) throws Exception {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	protected void restore(int complete, int failed) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public Object parseXML(JSONObject doc, int limit) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
}